package com.example.myBlogTest.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.myBlogTest.common.lang.Result;
import com.example.myBlogTest.dto.LoginRequest;
import com.example.myBlogTest.dto.UserResponse;
import com.example.myBlogTest.entity.User;
import com.example.myBlogTest.exception.NotFoundException;
import com.example.myBlogTest.service.UserService;
import com.example.myBlogTest.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.security.Security;

/**
 * Author: Lucy
 * Description:
 */
@RestController
public class AccountController {

    private UserService userService;

    private JwtUtils jwtUtils;

    public AccountController(UserService userService, JwtUtils jwtUtils) {
        this.userService = userService;
        this.jwtUtils = jwtUtils;
    }

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        System.out.println(loginRequest.getUsername());
        try {
            UserResponse userResponse = userService
                    .findByUsernameAndPassword(loginRequest.getUsername(), loginRequest.getPassword());

            String jwt = jwtUtils.generateToken(userResponse.getId());

            response.setHeader("Authorization", jwt);
            response.setHeader("Access-control-Expose-Headers", "Authorization");

            return Result.succ(userResponse);
        } catch (NotFoundException e) {
            return Result.fail(e.getMessage());
        }
    }

    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.succ(null);
    }
}
